package controller

import (
	"danmu/common"
	"danmu/model"
	"danmu/response"
	"danmu/util"
	"github.com/gin-gonic/gin"
)

func UploadFace(ctx *gin.Context)  {
	file,err:=ctx.FormFile("file")
	if err != nil {
		response.Fail(ctx,nil,"文件上传失败")
		return
	}
	file.Filename = "face"+util.RandomString(5)+ file.Filename
	if err := ctx.SaveUploadedFile(file, "./file/face/" + file.Filename); err != nil {
		response.Fail(ctx,nil,"保存文件失败")
		return
	}else{
		DB :=common.GetDB()
		var user model.User
		//从上下文中获取用户id
		id,_ :=ctx.Get("id")
		//根据id查找用户
		DB.First(&user, id)
		//保存头像
		DB.Model(&user).Update("face", file.Filename)
		response.Success(ctx,nil,"上传成功")
	}
}

func UploadCover(ctx *gin.Context){
	//上传视频封面
	img,err:=ctx.FormFile("img")
	if err != nil {
		response.Fail(ctx,nil,"封面上传失败")
		return
	}
	img.Filename = "img_" + util.RandomString(10)+ img.Filename
	if err := ctx.SaveUploadedFile(img, "./file/cover/" + img.Filename); err != nil {
		response.Fail(ctx,nil,"保存封面失败")
		return
	}
	response.Success(ctx,gin.H{"img":img.Filename},"上传成功")
}

func UploadCarousel(ctx *gin.Context){
	//上传轮播图
	img,err:=ctx.FormFile("img")
	if err != nil {
		response.Fail(ctx,nil,"封面上传失败")
		return
	}
	img.Filename = "carousel_" + util.RandomString(10)+ img.Filename
	if err := ctx.SaveUploadedFile(img, "./file/img/" + img.Filename); err != nil {
		response.Fail(ctx,nil,"保存轮播图失败")
		return
	}
	response.Success(ctx,gin.H{"img":img.Filename},"上传成功")
}

func UploadVideo(ctx *gin.Context)  {
	//视频文件
	video,err:=ctx.FormFile("video")
	if err != nil {
		response.Fail(ctx,nil,"视频上传失败")
		return
	}
	video.Filename = "video_" + util.RandomString(10)+ video.Filename
	if err := ctx.SaveUploadedFile(video, "./file/video/" + video.Filename); err != nil {
		response.Fail(ctx,nil,"保存视频失败")
		return
	}
	//从上下文中获取用户id
	id,_ :=ctx.Get("id")
	//返回结果
	response.Success(ctx,gin.H{"video":video.Filename,"uid":id},"上传成功")
}

